package com.jxl_dyw.UI;

import com.jxl_dyw.entity.Employee;
import com.jxl_dyw.hashMap.MyHashMap;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.Arrays;

/**
 * 员工表面板
 */
public class EmpUI extends JPanel {
    // 员工表格
    private JTable employeeTable;
    private static DefaultTableModel tableModel;
    // 员工信息文件路径
    static String filePath = "src/main/resources/Emps.csv";
    //用于存放员工的哈希表
    private static MyHashMap<String , Employee> employeeMap = new MyHashMap<>();
    //get方法
    public static MyHashMap<String, Employee> getEmployeeMap() {
        return employeeMap;
    }
    public EmpUI() throws IOException {
        setLayout(new BorderLayout());
        //用文件输入读取Emps.csv文件中的员工信息，并添加到哈希表中
        readEmployeesFromFile(filePath);
        // 创建表格模型员工 ID、姓名、性别、出生年月、工作年月、学历、职务、住址、电话
        String[] columnNames = {"员工 ID", "姓名", "性别", "出生年月", "工作年月", "学历", "部门", "住址", "电话"};

        tableModel = new DefaultTableModel(columnNames, 0); // 初始化为空表格

        // 读取哈希表的数据，并将对象中的数据添加到表格中
        for (Employee employee : employeeMap.values()) {
            Object[] rowData = {
                    employee.getEmpId(),
                    employee.getName(),
                    employee.getSex(),
                    employee.getBirthday(),
                    employee.getWorkday(),
                    employee.getEducation(),
                    employee.getPosition(),
                    employee.getAddress(),
                    employee.getPhone()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }

        // 创建表格
        employeeTable = new JTable(tableModel);
        // 创建一个滚动面板，并将员工表格添加到其中
        // 确保当员工表格的内容超出屏幕显示范围时，可以通过滚动
        JScrollPane scrollPane = new JScrollPane(employeeTable);
        add(scrollPane, BorderLayout.CENTER);

        // 创建顶部栏
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        // 查询按钮
        JButton checkButton = new JButton("查询员工");
        //增加搜索栏
        JTextField searchField = new JTextField(20);
        JButton addButton = new JButton("新增员工");
        //排序下拉列表框
        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.addItem("默认");
        comboBox.addItem("姓名a->z升序");
        comboBox.addItem("姓名z->a降序");



        topPanel.add(checkButton);
        topPanel.add(searchField);
        topPanel.add(addButton);
        topPanel.add(comboBox);

        add(topPanel, BorderLayout.NORTH);

        // 调整表格的行高
        for (int row = 0; row < employeeTable.getRowCount(); row++) {
            employeeTable.setRowHeight(30); // 调整行高以适应按钮
            //设置表格的字体
            employeeTable.setFont(new Font("宋体", Font.PLAIN, 14));
        }
        //添加按钮的监听器
        addButton.addActionListener(e -> {
            new AddEmpUI();
        });

        //为下拉框的选项添加事件监听器
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object selected = comboBox.getSelectedItem();
                if (selected.equals("姓名a->z升序")) {
                    //按姓名a->z升序
                    Object[] sortAsc = employeeMap.sortByNameAsc(employeeMap);
                    // 创建一个新的字符串数组，长度与sortAsc数组相同，并将sortAsc数组的内容复制到新数组中
                    String[] stringSortAsc = Arrays.copyOf(sortAsc, sortAsc.length, String[].class);
                    //刷新表格
                    refreshTablesort(stringSortAsc);

                } else if (selected.equals("姓名z->a降序")) {
                    //按姓名z->a降序
                    Object[] sortDesc = employeeMap.sortByNameDesc(employeeMap);
                    String[] stringSortDesc = Arrays.copyOf(sortDesc, sortDesc.length, String[].class);
                    //刷新表格
                    refreshTablesort(stringSortDesc);

                }else {
                    //默认刷新表格
                    refreshTable();
                }
            }
        });


        // 为查询按钮添加事件监听器
        checkButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchName = searchField.getText().trim();

                // 清空表格
                tableModel.setRowCount(0);

                if (searchName.isEmpty()) {
                    refreshTable();
                } else {
                    boolean found = false;
                    for (Employee employee : employeeMap.values()) {
                        if (employee.getName().contains(searchName) || employee.getName().contains(searchName)) {
                            Object[] rowData = {
                                    employee.getEmpId(),
                                    employee.getName(),
                                    employee.getSex(),
                                    employee.getBirthday(),
                                    employee.getWorkday(),
                                    employee.getEducation(),
                                    employee.getPosition(),
                                    employee.getAddress(),
                                    employee.getPhone()
                            };
                            tableModel.addRow(rowData);
                            found = true;
                        }
                    }
                    if (!found) {
                        JOptionPane.showMessageDialog(EmpUI.this, "未找到匹配的员工", "查询结果", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });

        // 添加鼠标右键菜单
        employeeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = employeeTable.rowAtPoint(e.getPoint());
                    if (row >= 0) {
                        showPopupMenu(e, row);
                    }
                }
            }
        });
    }

    // 刷新排序后的表格
    private void refreshTablesort(String []keys) {
        // 清空表格
        tableModel.setRowCount(0);

        // 遍历哈希表，将每个员工的信息添加到表格中
        for (String key: keys) {
            Object[] rowData = {
                    employeeMap.get(key).getEmpId(),
                    employeeMap.get(key).getName(),
                    employeeMap.get(key).getSex(),
                    employeeMap.get(key).getBirthday(),
                    employeeMap.get(key).getWorkday(),
                    employeeMap.get(key).getEducation(),
                    employeeMap.get(key).getPosition(),
                    employeeMap.get(key).getAddress(),
                    employeeMap.get(key).getPhone()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }
    }

    // 显示鼠标右键菜单
    private void showPopupMenu(MouseEvent e, int row) {
        JPopupMenu popupMenu = new JPopupMenu();

        JMenuItem editItem = new JMenuItem("编辑");
        editItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取选中的行数据
                String name = (String) tableModel.getValueAt(row, 1);
                Employee employee = employeeMap.get(name);

                // 弹出编辑窗口
                new EditEmpUI(employee);
            }
        });
        popupMenu.add(editItem);

        JMenuItem deleteItem = new JMenuItem("删除");
        deleteItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取选中的行数据
                String name = (String) tableModel.getValueAt(row, 1);
                Employee employee = employeeMap.get(name);

                // 弹出确认对话框
                int confirm = JOptionPane.showConfirmDialog(EmpUI.this, "确定要删除员工 " + employee.getName() + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 删除哈希表中的员工
                    employeeMap.remove(name);
                    tableModel.removeRow(row);
                }
                //将新的数据写入文件中
                try {
                    writeEmployeesToFile(filePath);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        popupMenu.add(deleteItem);

        popupMenu.show(e.getComponent(), e.getX(), e.getY());
    }

    //将哈希表中的数据写入到CSV文件中
    public static void writeEmployeesToFile(String filePath) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {

            // 遍历哈希表，将每个员工的信息写入CSV文件
            for (Employee employee : employeeMap.values()) {
                writer.write(String.join(",",
                        employee.getEmpId(),
                        employee.getName(),
                        employee.getSex(),
                        employee.getBirthday(),
                        employee.getWorkday(),
                        employee.getEducation(),
                        employee.getPosition(),
                        employee.getAddress(),
                        employee.getPhone()
                ));
                writer.newLine();
            }
        }
    }


    // 刷新表格，重新加载哈希表中的数据
    public static void refreshTable() {
        loadEmployeeDataToTable();
    }


    // 从哈希表中加载员工数据到表格
    private static void loadEmployeeDataToTable() {
        // 清空表格
        tableModel.setRowCount(0);

        // 遍历哈希表，将每个员工的信息添加到表格中
        for (Employee employee : employeeMap.values()) {
            Object[] rowData = {
                    employee.getEmpId(),
                    employee.getName(),
                    employee.getSex(),
                    employee.getBirthday(),
                    employee.getWorkday(),
                    employee.getEducation(),
                    employee.getPosition(),
                    employee.getAddress(),
                    employee.getPhone()
            };
            tableModel.addRow(rowData); // 将每一行数据添加到表格模型中
        }
    }

    // 读取 CSV 文件并将数据添加到 employeeMap 中
    public void readEmployeesFromFile(String filePath) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分隔每一行
                String[] fields = line.split(",");

                // 创建 Employee 对象
                Employee employee = new Employee(
                        fields[0],
                        fields[1],
                        fields[2],
                        fields[3],
                        fields[4],
                        fields[5],
                        fields[6],
                        fields[7],
                        fields[8]
                );

                // 将 Employee 对象添加到哈希表中，以员工的名字作为键
                employeeMap.put(employee.getName(), employee);
            }
        }
    }

}
